from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
import os
from email.header import Header
from smtplib import SMTP_SSL

def send_email(receiver, content, config):
    host_sever = 'smtp.qq.com'
    sender_qq = '1659078644'
    pwd = 'jxqqcwpgokqrbbad'
    sender_qq_email = '1659078644@qq.com'

    smtp = SMTP_SSL(host_sever)
    smtp.set_debuglevel(0)
    smtp.ehlo(host_sever)
    smtp.login(sender_qq, pwd)

    files = os.listdir('./tensorboard_fig/' + config.exp_name)
    msg = MIMEMultipart('related')
    msg.attach(MIMEText(content, 'plain', 'utf-8'))
    for i in files:
        with open('./tensorboard_fig/' + config.exp_name + '/' + i , 'rb',) as png:
            fig = MIMEImage(png.read(), i.split('.')[-1])
            fig.add_header('Content-Disposition', 'attachment', filename=i)
            msg.attach(fig)
    msg['Subject'] = Header(config.exp_name, 'utf-8')
    msg['from'] = sender_qq_email
    msg['to'] = receiver

    smtp.sendmail(sender_qq_email, receiver, msg.as_string())
    smtp.close()
    print('Successfully send')

def mail_txt(writer_train_loss, write_train_accuracy, test_loss, test_accuracy, config):
    content = []
    for key, values in config.items():
        s = "%s:%s"%(key, values)
        content.append(s)

    data_dict = {'train_accuracy':writer_train_loss, 'train_epoch': write_train_accuracy, 'test_accuracy': test_loss, 'test_epoch': test_accuracy}
    content.append('result:')
    for i, values in data_dict.items():
        s = '%s:%s'%(i, values)
        content.append(s)
    content = '\n'.join(content)
    return content




